import java.time.*;
import java.util.*;
import java.util.stream.Collectors;
import java.io.*;import java.io.Serializable;

class Ticket implements Serializable {
    private  String ticketId;
    private  Session session;
    private  List<Seat> seats;
    private  float totalPrice;
    private  LocalDateTime purchaseTime;
    private  boolean refunfed;
    private  User purchasedBy;

    public Ticket(Session session,List<Seat> seats,User purchasedBy){
        this.ticketId=UUID.randomUUID().toString().substring(0,8).toUpperCase();
        this.session=session;
        this.seats=seats;
        this.totalPrice=calculateTotalPrice();
        this.purchaseTime=LocalDateTime.now();
        this.refunfed=false;
        this.purchasedBy=purchasedBy;
    }

    private float calculateTotalPrice(){
        long childCount=seats.stream().filter(seat->seat.getRow()<=3).count();

        float basePrice= session.getPrice();
        float total=0;

        for(Seat seat:seats){
            if(seat.getRow()<=3){
                total+=basePrice*0.5;
            }
            else{
                total += basePrice;
            }
        }

        if(session.getTime().getHour()<10){
            total*=0.9;
        }

        return total;
    }

    public float refund(){
        if(refunfed){
            return 0;
        }

        refunfed=true;
        session.releaseSeats(seats);

        long hoursBefore=Duration.between(LocalDateTime.now(),session.getTime()).toHours();

        if(hoursBefore>24){
            return totalPrice;
        }
        else if(hoursBefore>1){
            return totalPrice*0.9f;
        }
        else{
            return 0;
        }
    }
    public String getTicketId(){return ticketId;}
    public Session getSession(){return session;}
    public List<Seat> getSeats(){return seats;}
    public float getTotalPrice(){return totalPrice;}
    public LocalDateTime getPurchaseTime(){return purchaseTime;}
    public boolean isRefunfed(){return refunfed;}
    public User getPurchasedBy(){return purchasedBy;}

    @Override
    public String toString(){
        return String.format("票号：%s\n影片“%s\n场次：%s\n影厅：%s\n时间：%s\n座位：%s\n总价：%2f元",ticketId,session.getMovie().getTitle(),session.getSessionId(),session.getRoom().getName(),session.getTime(),seats.stream().map(Seat::toString).collect(Collectors.joining(",")),totalPrice);
    }
}
